import 'dart:async';
import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/event_bus_global.dart';
import 'package:wch/model/device_upgrade_model.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/widget/text_widget.dart';

import '../constant/resource_constant.dart';
import '../constant/text_constant.dart';
import '../model/login_custom.dart';
import '../utils/toast_utils.dart';
import 'login_widget.dart';
import 'overlay_loading_popscope.dart';
import 'padding_widget.dart';

///登录的父容器
class LoginContainer extends StatelessWidget {
  LoginContainer({super.key, this.child, this.horPadding = 30, this.verTopPadding = 20, this.verBottomPadding = 20, this.backgroundColor = themeBGC, });

  final double horPadding;
  final double verTopPadding;
  final double verBottomPadding;
  final Color backgroundColor;

  static double horPaddingConstant = 30;

  Widget? child;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: backgroundColor,
      width: ScreenUtil().screenWidth,
      height: ScreenUtil().screenHeight,
      padding: EdgeInsets.fromLTRB(
          horPadding, verTopPadding, horPadding, verBottomPadding),
      child: child ?? Container(),
    );
  }
}

///公共父容器
class CommonContainer extends StatelessWidget {
  CommonContainer(
      {super.key, this.child, this.horPadding = 15, this.verPadding = 20, this.backgroundColor = Colors.white});

  final double horPadding;
  final double verPadding;

  final Color backgroundColor;

  Widget? child;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding:
          EdgeInsets.symmetric(horizontal: horPadding, vertical: verPadding),
      decoration: BoxDecoration(
          color: backgroundColor, borderRadius: BorderRadius.circular(20.h)),
      child: child ?? Container(),
    );
  }
}

///带阴影的 container
class ShadowContainer extends StatelessWidget {
  ShadowContainer(
      {super.key, this.child, this.horPadding = 15, this.verPadding = 20, required this.height, required this.width});

  final double horPadding;
  final double verPadding;
  final double height;
  final double width;

  Widget? child;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: height,
      // padding:
          // EdgeInsets.symmetric(horizontal: horPadding, vertical: verPadding),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(7.5.h)),
          boxShadow: const [
            // BoxShadow(
            //     color: Colors.black12,
            //     offset: Offset(5.0, 5.0), //阴影xy轴偏移量
            //     blurRadius: 15.0, //阴影模糊程度
            //     spreadRadius: 1.0 //阴影扩散程度
            // )
          ]
      ),
      child: child ?? Container(),
    );
  }
}

///公共 scaffold
class CommonScaffold extends StatelessWidget {
  const CommonScaffold({Key? key, required this.title, required this.body, this.rightBtn})
      : super(key: key);

  final String title;
  final Widget body;
  final Widget? rightBtn;

  @override
  Widget build(BuildContext context) {
    return OverlayLoadingPopScope(
      child: Scaffold(
        // resizeToAvoidBottomInset: false,
        backgroundColor: Color(0xFFF8F9FB),
        appBar: AppBar(
          elevation: 0,
          title: Text(title),
          backgroundColor: Colors.white,
          foregroundColor: Colors.black,
          centerTitle: true,
          leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: const Icon(
              Icons.arrow_back_ios,
              color: Colors.black,
            ),
          ),
          actions: rightBtn == null ? [] : [
            rightBtn!
          ],
        ),
        body: body,
      ),
    );
  }
}

///tab radio 控件
class TabRadioWidget extends StatefulWidget {
  TabRadioWidget(this.title,
      {Key? key,
      this.isSelect = false,
      this.selectColor = const Color(0xFF5A7BED),
      this.normalColor = const Color(0xFF3E3F42),
      this.callback,
      this.fontSize = 15})
      : super(key: key);

  final String title;
  final Color selectColor;
  final Color normalColor;
  final bool isSelect;
  double fontSize = 15;

  Function? callback;

  @override
  State<TabRadioWidget> createState() => _TabRadioWidgetState();
}

class _TabRadioWidgetState extends State<TabRadioWidget> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (widget.callback != null) {
          widget.callback!();
        }
      },
      child: Column(
        children: [
          Text(
            widget.title,
            style: TextStyle(
                color:
                    widget.isSelect ? widget.selectColor : widget.normalColor,
                fontSize: f15TextSize.w,
                decoration: TextDecoration.none),
          ),
          VerPadding(2.w),
          _getLine(isSelected: widget.isSelect),
        ],
      ),
    );
  }

  Widget _getLine({isSelected = Bool}) {
    ///高度4
    double height = 9.5.h;
    double width = 24.w;
    if (isSelected) {
      return Container(
        width: width,
        height: height,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(height / 2)),
          gradient: LinearGradient(
            colors: [Color(0x995A7BED), Color(0x005A7BED)],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          color: themeColor,
        ),
      );
    } else {
      return Container();
    }
  }
}

///单选按钮
class CommonRadiusBtn extends StatelessWidget {
  CommonRadiusBtn(
      {Key? key,
        required this.width,
        required this.height,
        this.callback,
        required this.title,
        this.corner = 0,
        this.borderColor = themeColor,
        this.backgroundColor = Colors.transparent,
        this.textColor = themeColor})
      : super(key: key);

  final double width;
  final double height;
  final String title;
  Color borderColor;
  Color backgroundColor;
  Color textColor;
  double corner;
  final Function? callback;


  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (callback != null) {
          callback!();
        }
      },
      child: Container(
        width: width,
        height: height,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(corner == 0 ? height / 2 : corner),
            border: Border.all(color: borderColor, width: 0.5.h),
            color: backgroundColor),
        child: F13TitleText(
          title,
          color: textColor,
        ),
      ),
    );
  }
}
//
//常用组件
//
class CommonBtn extends StatelessWidget {
  CommonBtn(
      {Key? key, this.isEnable = true, required this.title, this.callback, this.fontSize = 16})
      : super(key: key);

  ///不可用时颜色偏灰
  bool isEnable = true;
  final String title;
  Function? callback;
  final double? fontSize;

  ///时间戳，防止短时间内多次点击按钮产生事件
  int lastTimeStamp = 0;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(21.5.h),
        ),
        child: GestureDetector(

          onTap: () {
            int curTimeStamp = DateTime.now().microsecondsSinceEpoch ~/ 1000;
            debugPrint('curTimeStamp=$curTimeStamp');
            if (curTimeStamp - lastTimeStamp < 1500) {
              ///2次点击间隔小于1.5秒，跳出
              LogUtils.log('跳出');
              lastTimeStamp = curTimeStamp;
              return;
            }
            lastTimeStamp = curTimeStamp;
            if (callback != null && isEnable) {
              callback!();
            }
          },
          child: Container(
            alignment: Alignment.center,
            height: 43.0.h,
            padding: const EdgeInsets.symmetric(horizontal: 0),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(21.5.h),
                color: isEnable ? btnBGC : btnDisableBGC),
            child: Text(
              title,
              style: TextStyle(
                  color: Colors.white, fontSize: fontSize, decoration: TextDecoration.none),
            ),
          ),
        ),
      ),
    );
  }
}

///线条控件
class LineWidget extends StatelessWidget {
  LineWidget(
      {Key? key,
      required this.width,
      required this.height,
      this.isCorner,
      this.color = lineColor})
      : super(key: key);

  final double width;
  final double height;
  Color color;

  ///是否需要圆角
  final bool? isCorner;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(
            (isCorner != null && isCorner!) ? height / 2 : 0),
        color: color,
      ),
      width: width,
      height: height,
    );
  }
}

///输入密码
class InputPass extends StatefulWidget {
  const InputPass({super.key, this.callback, this.title = inputPassHint, required this.node});

  ///callback
  ///(len:int content:String)
  /// 文本长度  文本内容
  final Function? callback;
  final String title;
  final FocusNode node;

  @override
  State<InputPass> createState() => _InputPassState();
}

class _InputPassState extends State<InputPass> {
  bool isSelected = false;
  TextEditingController controller = TextEditingController();

  @override
  void initState() {
    controller.addListener(() {

      var text = controller.text;
      var num = -1;

      if (text.isNotEmpty) {
        num = text.length;
      }

      if (widget.callback != null) {
        widget.callback!(num, text);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 15.0.h),
      child: Column(
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset(loginPassIcon, width: 12.3.w, height: 17.3.h),
              HorPadding(10.w),
              Expanded(
                  child: Column(
                children: [
                  TextField(
                    maxLines: 1,
                    obscureText: !isSelected,
                    keyboardType: TextInputType.text,
                    style: TextStyle(fontSize: 14.w, color: F1TextColor),
                    cursorColor: themeColor,
                    controller: controller,
                    focusNode: widget.node,
                    maxLength: 16,
                    inputFormatters: [
                      FilteringTextInputFormatter(RegExp("[a-z0-9A-Z]"),
                          allow: true),
                    ],
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      // 取消输入框的下划线
                      counterText: '',
                      focusColor: themeColor,
                      hintText: widget.title,
                      hintStyle: const TextStyle(color: hintColor),
                    ),
                  ),
                ],
              )),
              HorPadding(10.w),
              GestureDetector(
                child: Image.asset(isSelected ? showPassIcon : hidePassIcon,
                    width: 14.3.w, height: 14.3.w),
                onTap: () {
                  if (widget.callback != null) {
                    bool state = !isSelected;

                    setState(() {
                      isSelected = state;
                    });
                  }
                },
              ),
              HorPadding(5.w)
            ],
          ),
          Divider(
            height: 0.5.h,
            color: lineColor,
          )
        ],
      ),
    );
  }
}

///输入验证码
///TODO：未和账号控件绑定，一点击就倒计时
class InputValidCode extends StatefulWidget {
  InputValidCode({super.key, this.callback, this.isEnabled = true, required this.node});

  ///callback
  ///(len:int content:String)
  /// 文本长度  文本内容
  final Function? callback;
  final FocusNode node;

  ///是否可以点击发送按钮，如果未输入手机号则传入 false
  bool isEnabled;

  @override
  State<InputValidCode> createState() => _InputValidCodeState();
}

class _InputValidCodeState extends State<InputValidCode> {
  ///已发送验证码
  bool sended = false;
  int countdown = 60;
  Timer? timer;
  String text = sendCode;

  TextEditingController controller = TextEditingController();

  bool isContinue = true;
  String lastText = '';

  StreamSubscription? btnStatusSubscription;

  @override
  void initState() {
    btnStatusSubscription = globalEventBus.on<RefreshSendCodeModel>().listen((onData){
      bool state = true;
      setState(() {
        sended = state;
      });
      countdownLogic();
    });

    controller.addListener(() {
      if (controller.text.length - 2 >= lastText.length) {
        controller.text = lastText;
        return;
      }
      if (!isContinue) {
        isContinue = true;
        return;
      }
      if (controller.text.isEmpty)  return;
      var text = controller.text;
      String last = text.substring(text.length-1, text.length);
      if (last != '0' && last != '1' && last != '2'
          && last != '3' && last != '4' && last != '5'
          && last != '6' && last != '7' && last != '8' && last != '9') {
        isContinue = false;
        controller.text = text.substring(0, text.length-1);
        lastText = controller.text;
        return;
      }
      lastText = controller.text;

      var num = text.length;

      if (widget.callback != null) {
        widget.callback!(num, text);
      }
    });
  }

  @override
  void dispose() {
    if (timer != null) {
      timer!.cancel();
    }
    btnStatusSubscription?.cancel();
    super.dispose();
  }

  void countdownLogic() {
    if (timer != null) {
      return;
    }

    timer = Timer.periodic(const Duration(seconds: 1), (t) {
      countdown--;
      if (countdown < 0) {
        countdown = 60;
        timer!.cancel();
        timer = null;
        sended = false;
        text = '再次获取';
      }

      setState(() {
        countdown;
        sended;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 15.0.h),
      child: Column(
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset(loginPassIcon, width: 12.3.w, height: 17.3.h),
              HorPadding(10.w),
              Expanded(
                  child: Column(
                children: [
                  TextField(
                    maxLength: 6,
                    maxLines: 1,
                    cursorColor: themeColor,
                    focusNode: widget.node,
                    keyboardType: TextInputType.number,
                    style: TextStyle(fontSize: 14.w, color: F1TextColor),
                    controller: controller,
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      // 取消输入框的下划线
                      counterText: '',
                      focusColor: themeColor,
                      hintText: inputCodeHint,
                      hintStyle: TextStyle(color: hintColor),
                    ),
                  ),
                ],
              )),
              HorPadding(10.w),
              GestureDetector(
                child: !sended
                    ? Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: 8.w, vertical: 10.h),
                        decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(5.h)),
                            color: btnDisableBGC),
                  child: F11TitleText(sendCode, color: themeColor),
                      )
                    : F11TitleText('$countdown秒后重新获取', color: themeColor),
                onTap: () {
                  if (!widget.isEnabled && !sended) {
                    ToastUtils.showToast(msg: '请输入正确的手机号码');
                    return;
                  }
                  if (sended) {
                    return;
                  }
                  // bool state = true;
                  // setState(() {
                  //   sended = state;
                  // });
                  // countdownLogic();

                  if (widget.callback != null) {
                    widget.callback!(-1, controller.text);
                  }
                },
              ),
              HorPadding(5.w)
            ],
          ),
          Divider(
            height: 0.5.h,
            color: lineColor,
          )
        ],
      ),
    );
  }
}
